package com.ny.zuoye2567.dao.dao;

import com.ny.zuoye2567.dao.DbUntil;
import com.ny.zuoye2567.dao.shiti.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {
    private DbUntil dbUntil = new DbUntil();

    @Override
    public Student login(String name, String password) throws Exception {
        Connection connection = dbUntil.getCon();
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,password);

        ResultSet resultSet = preparedStatement.executeQuery();
        Student student = new Student();

        if(resultSet.next()){
            int id = resultSet.getInt("student_id");
            String sname = resultSet.getString("name");
            String phone = resultSet.getString("phone");
            String sPassword = resultSet.getString("password");

            student.setStudentId(id);
            student.setName(sname);
            student.setPhone(phone);
            student.setPassword(sPassword);
            return student;
        }
        return null;
    }

    @Override
    public int insertStudent(Student student) throws SQLException, ClassNotFoundException {
        Connection connection = dbUntil.getCon();
        String sql = "insert into students(name,phone,password) values(?,?,?)";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,student.getName());
        preparedStatement.setString(2,student.getPhone());
        preparedStatement.setString(3,student.getPassword());
        int i = preparedStatement.executeUpdate();

        return i;
    }


}
